package com.tangruojie.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 为什么你的 @WebFilter 能被正确注册？
 * 因为在 Servlet 3.0 规范中，只要类路径下有 @WebFilter 注解类，并且你的容器支持注解扫描（如 Tomcat 7+），它就会自动注册 Filter。
 */
@WebFilter(urlPatterns = "/*")
public class EncodingLogFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 设置编码
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        // 日志记录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        System.out.println("[日志] 请求路径: " + req.getRequestURI());
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("[日志] 响应完成: " + req.getRequestURI());
    }

    @Override
    public void destroy() {

    }
}
